import { ConfigManager } from './config.js';
import { BridgeServer } from './server.js';
import { ConfigError, BridgeError } from './types.js';

async function main(): Promise<void> {
  try {
    console.log('🚀 Starting Claude Bridge...');

    // Parse CLI arguments and create configuration
    const config = await ConfigManager.fromCLI();

    console.log('✅ Configuration loaded:', {
      url: config.url,
      model: config.model,
      port: config.port,
      host: config.host,
      maxTokens: config.maxTokens,
      timeout: config.timeout,
      logLevel: config.logLevel,
      apiKey: config.apiKey.substring(0, 8) + '...',
    });

    // Create and start server
    const server = new BridgeServer(config);
    await server.start();

  } catch (error) {
    if (error instanceof ConfigError) {
      console.error('❌ Configuration Error:', error.message);
      console.error('\nUsage:');
      console.error('  claude-bridge -u <api-url> -m <model> -k <api-key>');
      console.error('\nExample:');
      console.error('  claude-bridge -u https://api.openai.com/v1 -m gpt-4 -k sk-your-key');
      console.error('\nFor more options, use: claude-bridge --help');
      process.exit(1);
    }

    if (error instanceof BridgeError) {
      console.error('❌ Bridge Error:', error.message);
      process.exit(1);
    }

    console.error('❌ Unexpected Error:', error instanceof Error ? error.message : String(error));
    if (error instanceof Error && error.stack) {
      console.error(error.stack);
    }
    process.exit(1);
  }
}

// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
  process.exit(1);
});

// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
  console.error('❌ Uncaught Exception:', error);
  process.exit(1);
});

main();